// 游戏主JS文件

// 初始化游戏
function initializeGame() {
    console.log('游戏初始化完成');
    
    // 绑定各种游戏功能
    bindChatFeatures();
    bindOnlinePlayersDisplay();
    bindPrivateChat();
    
    // 初始化SignalR连接
    initializeSignalR();
}

// 绑定聊天功能
function bindChatFeatures() {
    // 绑定发送世界消息功能
    const sendWorldChatBtn = document.getElementById('send-world-chat');
    const worldChatInput = document.getElementById('world-chat-input');

    if (sendWorldChatBtn && worldChatInput) {
        sendWorldChatBtn.addEventListener('click', function () {
            const message = worldChatInput.value.trim();

            if (message) {
                // 清空输入框
                worldChatInput.value = '';

                // 在聊天窗口中显示自己发送的消息
                updateWorldChat(currentPlayerName, message, true);
                
                // 通过SignalR发送消息到服务器
                if (connection && connection.state === signalR.HubConnectionState.Connected) {
                    connection.invoke("发送世界消息", currentPlayerName, message).catch(function (err) {
                        console.error(err.toString());
                    });
                }
            }
        });

        // 支持回车发送消息
        worldChatInput.addEventListener('keypress', function (e) {
            if (e.key === 'Enter') {
                sendWorldChatBtn.click();
            }
        });
    }
}

// 更新世界聊天显示
function updateWorldChat(sender, message, isSelf = false) {
    const chatMessages = document.getElementById('world-chat-messages');
    if (chatMessages) {
        const messageElement = document.createElement('div');
        messageElement.className = 'chat-message ' + (isSelf ? 'self-message' : 'other-message');
        messageElement.innerHTML = `
            <span class="sender">${sender}</span>
            <span class="message-content">${message}</span>
            <span class="timestamp">${new Date().toLocaleTimeString()}</span>
        `;
        chatMessages.appendChild(messageElement);
        chatMessages.scrollTop = chatMessages.scrollHeight;
    }
}

// 更新小队聊天显示
function updatePartyChat(sender, message, isSelf = false) {
    const chatMessages = document.getElementById('party-chat-messages');
    if (chatMessages) {
        const messageElement = document.createElement('div');
        messageElement.className = 'chat-message ' + (isSelf ? 'self-message' : 'other-message');
        messageElement.innerHTML = `
            <span class="sender">${sender}</span>
            <span class="message-content">${message}</span>
            <span class="timestamp">${new Date().toLocaleTimeString()}</span>
        `;
        chatMessages.appendChild(messageElement);
        chatMessages.scrollTop = chatMessages.scrollHeight;
    }
}

// 更新私聊显示
function updatePrivateChat(sender, message, isSelf = false) {
    const chatMessages = document.getElementById('private-chat-messages');
    if (chatMessages) {
        const messageElement = document.createElement('div');
        messageElement.className = 'chat-message ' + (isSelf ? 'self-message' : 'other-message');
        messageElement.innerHTML = `
            <span class="sender">${sender}</span>
            <span class="message-content">${message}</span>
            <span class="timestamp">${new Date().toLocaleTimeString()}</span>
        `;
        chatMessages.appendChild(messageElement);
        chatMessages.scrollTop = chatMessages.scrollHeight;
    }
}

// 显示系统通知
function showNotification(title, content, type = 'info') {
    // 创建通知元素
    const notification = document.createElement('div');
    notification.className = `system-notification ${type}`;
    notification.innerHTML = `
        <div class="notification-header">
            <span class="notification-title">${title}</span>
            <button class="close-notification">&times;</button>
        </div>
        <div class="notification-content">${content}</div>
    `;

    // 添加到页面
    document.body.appendChild(notification);

    // 绑定关闭按钮事件
    const closeButton = notification.querySelector('.close-notification');
    closeButton.addEventListener('click', () => {
        notification.style.display = 'none';
        document.body.removeChild(notification);
    });

    // 3秒后自动关闭
    setTimeout(() => {
        if (notification.parentNode) {
            notification.style.display = 'none';
            document.body.removeChild(notification);
        }
    }, 3000);
}

// 绑定在线玩家列表显示功能
function bindOnlinePlayersDisplay() {
    // 可以在这里添加显示/隐藏在线玩家列表的按钮绑定
    const toggleButton = document.getElementById('toggle-online-players');
    const onlinePlayersPanel = document.getElementById('online-players-panel');

    if (toggleButton && onlinePlayersPanel) {
        toggleButton.addEventListener('click', function () {
            onlinePlayersPanel.style.display = onlinePlayersPanel.style.display === 'none' ? 'block' : 'none';
        });
    }
}

// 绑定私聊功能
function bindPrivateChat() {
    const sendPrivateChatBtn = document.getElementById('send-private-chat');
    const privateChatInput = document.getElementById('private-chat-input');

    if (sendPrivateChatBtn && privateChatInput) {
        sendPrivateChatBtn.addEventListener('click', function () {
            const message = privateChatInput.value.trim();

            if (message) {
                // 清空输入框
                privateChatInput.value = '';

                // 在私聊窗口中显示自己发送的消息
                updatePrivateChat(currentPlayerName, message, true);
            }
        });
    }
}

// 初始化SignalR连接
let connection;
let currentPlayerName = "玩家";

function initializeSignalR() {
    // 创建SignalR连接
    connection = new signalR.HubConnectionBuilder()
        .withUrl("/gamehub")
        .build();

    // 接收世界消息
    connection.on("接收世界消息", function (user, message) {
        updateWorldChat(user, message);
    });

    // 接收小队消息
    connection.on("接收小队消息", function (user, message) {
        updatePartyChat(user, message);
    });

    // 接收私聊消息
    connection.on("接收私聊消息", function (user, message) {
        updatePrivateChat(user, message);
    });

    // 接收系统通知
    connection.on("接收管理员通知", function (通知) {
        showNotification(通知.标题, 通知.内容, 通知.类型 || 'info');
    });

    // 玩家加入通知
    connection.on("玩家加入", function (playerName, location) {
        console.log(`玩家 ${playerName} 加入了游戏，在 ${location}`);
        showNotification("玩家上线", `${playerName} 加入了游戏`, "success");
    });

    // 玩家离开通知
    connection.on("玩家离开", function (playerName) {
        console.log(`玩家 ${playerName} 离开了游戏`);
        showNotification("玩家下线", `${playerName} 离开了游戏`, "warning");
    });

    // 接收在线玩家列表
    connection.on("接收在线玩家列表", function (players) {
        console.log("在线玩家列表:", players);
        // 可以在这里更新在线玩家列表UI
    });

    // 连接成功
    connection.start().then(function () {
        console.log("SignalR连接成功");
        
        // 通知服务器玩家已登录
        connection.invoke("玩家登录", currentPlayerName, "主城").catch(function (err) {
            console.error(err.toString());
        });
    }).catch(function (err) {
        console.error("SignalR连接失败:", err.toString());
    });
}

// 创建小队
function createParty() {
    if (connection && connection.state === signalR.HubConnectionState.Connected) {
        connection.invoke("创建小队").catch(function (err) {
            console.error(err.toString());
        });
    }
}

// 加入小队
function joinParty(partyId) {
    if (connection && connection.state === signalR.HubConnectionState.Connected) {
        connection.invoke("加入小队", partyId).catch(function (err) {
            console.error(err.toString());
        });
    }
}

// 离开小队
function leaveParty(partyId) {
    if (connection && connection.state === signalR.HubConnectionState.Connected) {
        connection.invoke("离开小队", partyId).catch(function (err) {
            console.error(err.toString());
        });
    }
}

// 初始化冒险页面
function initializeAdventure(locationName) {
    // 设置当前地点
    const locationElement = document.getElementById('adventure-location');
    if (locationElement) {
        locationElement.textContent = locationName;
    }
    
    // 显示冒险页面
    const adventurePage = document.getElementById('adventure-page');
    const worldPage = document.getElementById('world-page');
    
    if (adventurePage) adventurePage.style.display = 'flex';
    if (worldPage) worldPage.style.display = 'none';
    
    console.log(`进入冒险: ${locationName}`);
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function () {
    initializeGame();
});